package com.sm.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.sm.auth.entity.UmsMenu;
import com.sm.auth.entity.UmsRole;
import com.sm.auth.entity.UmsSysUser;
import com.sm.auth.mapper.UserMapper;
import com.sm.auth.vo.LoginUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UmsSysUser sysUser = sysUserMapper.selectUserByUserName(username);
        log.info("用户信息：{}", sysUser);
        //根据角色获取权限
        if (ObjectUtil.isNotNull(sysUser)) {
            List<UmsRole> roleList = sysUser.getRoleList();
            List<Long> roleIds = roleList.stream().map(UmsRole::getRoleId).collect(Collectors.toList());
            log.info("角色ID：{}", roleIds);
            //查询所有菜单
            List<UmsMenu> umsMenuList = sysUserMapper.selectMenuByRoleIds(roleIds);
            log.info("菜单：{}", umsMenuList);
            List<String> perms = umsMenuList.stream().map(UmsMenu::getPerms).collect(Collectors.toList());
            sysUser.setPermissionList(perms);
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(sysUser.getId());
        loginUserVo.setSysUser(sysUser);
        return loginUserVo;
    }
}